<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>webRTC实现纯前端录音功能</title>
    <style type="text/css">
        video{
            filter: brightness(1.7);
        }
    </style>
</head>
<body>
<video autoplay playsinline id="player"></video>

<video id="recplayer" playsinline></video>
<button id="record">Start Record</button>
<button id="recplay" disabled>Play</button>
<button id="download" disabled>Download</button>
<script type="text/javascript" src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<script type="text/javascript">
    'use strict';

    var videoplay=document.querySelector('#player');
    function gotMediaStream(stream){
        window.stream=stream;
        videoplay.srcObject=stream;
        videoplay.volume=0;

        console.log(stream)
        let audioTrack=stream.getAudioTracks()[0];
        let audioCons=audioTrack.getSettings();
        console.log(audioCons)
        // let audioContext = window.AudioContext || window.webkitAudioContext;
        // let context = new audioContext(); //创建一个管理、播放声音的对象
        // let volume=context.createGain();
        // // oscillator.connect(volume);
        // volume.connect(context.destination); //音量连接扬声器
        // volume.gain.value=0;
        // console.log(volume)
        navigator.mediaDevices.enumerateDevices().then((data)=>{
            console.log(data)
        })
        // return navigator.mediaDevices.enumerateDevices();
    }
    function handleError(err){
        console.log('getUserMedia error:',err);
    }

    function start(){
        if(!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia){
            console.log('getUserMedia is not supported!');
            return;
        }else{
            var constraints={
                // video:false,
                video:{
                    width:640,
                    height:480,
                    frameRate:60
                },
                // audio:false
                audio:{
                    noiseSuppression:true,
                    echoCancellation:true
                }
            }
            navigator.mediaDevices.getUserMedia(constraints)
                .then(gotMediaStream)
                .catch(handleError);

        }
    }
    start();
    // 如果配置如摄像头之类可以自定义，则最好在切换摄像头的时候把对音视频的设置函数给重新调用一遍

    // 这个可以是一个单独的封装
    let recvideo=document.querySelector('#recplayer');
    let btnRecord=document.querySelector('#record');
    let btnPlay=document.querySelector('#recplay');
    let btnDownload=document.querySelector('#download');

    var buffer;
    var mediaRecorder;

    function handleDataAvailable(e){
        // console.log(e)
        if(e && e.data && e.data.size>0){
            buffer.push(e.data);
        }
    }

    function startRecord(){

        // 定义一个接收数组
        buffer=[];

        var options={
            mimeType:'video/webm;codecs=vp8'
        }
        if(!MediaRecorder.isTypeSupported(options.mimeType)){
            console.error(`${options.mimeType} is not supported`);
            return;
        }

        try{
            mediaRecorder=new MediaRecorder(window.stream,options);
        }catch(e){
            console.error('Fail to create');
            return;
        }
        mediaRecorder.ondataavailable=handleDataAvailable;
        // 时间片
        mediaRecorder.start(10);

    }
    function stopRecord(){
        mediaRecorder.stop();
    }
    btnRecord.onclick=()=>{
        if(btnRecord.textContent==='Start Record'){
            startRecord();
            btnRecord.textContent='Stop Record';
            btnPlay.disabled=true;
            btnDownload.disabled=true;
        }else{
            stopRecord();
            btnRecord.textContent='Start Record';
            btnPlay.disabled=false;
            btnDownload.disabled=false;
        }
    }
    btnPlay.onclick=()=>{
        var blob=new Blob(buffer,{type: 'video/webm'});
        recvideo.src=window.URL.createObjectURL(blob);
        recvideo.srcObject=null;
        recvideo.controls=true;
        recvideo.play();
    }
    btnDownload.onclick=()=>{
        var blob=new Blob(buffer,{type:'video/webm'});
        var url=window.URL.createObjectURL(blob);
        var a=document.createElement('a');
        a.href=url;
        a.style.display='none';
        a.download='recording.webm';
        a.click();
    }
</script>
</body>
</html>
